﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;

namespace MobiMenu.Restaurant.Web.Utility
{
    public static class JsonHelper<T>
    {
        static JsonHelper()
        { }

        /// <summary>  
        /// 序列化为JSON对象  
        /// </summary>  
        /// <param name="obj"></param>  
        /// <returns></returns>  
        public static string WriteObject(T obj)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            var mstream = new MemoryStream();
            serializer.WriteObject(mstream, obj);
            byte[] Bytes = new byte[mstream.Length];
            mstream.Position = 0;
            mstream.Read(Bytes, 0, (int)mstream.Length);
            return Encoding.UTF8.GetString(Bytes);
        }

        /// <summary>  
        /// JSON对象反序列化  
        /// </summary>  
        /// <param name="data"></param>  
        /// <returns></returns>  
        public static T ReadObject(string data)
        {
            var mstream = new MemoryStream(Encoding.UTF8.GetBytes(data));
            var serializer = new DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(mstream);
        }
    }  
}